package XML;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XMLWriter {
	static File f;
		private static DocumentBuilderFactory docFactory;
		private static DocumentBuilder docBuilder;
		private static Document doc;
		private static Element parentElement,childElement;
		private static Element rootElement;
		private static TransformerFactory transformerFactory;
		private static Transformer transformer;
		private static DOMSource source;
		private static StreamResult result;
		private static ArrayList<Element> list;
		
		
	public static void instantiate(String rootElementName) throws ParserConfigurationException, TransformerConfigurationException{
		f = new File("presentation.xml");
		docFactory = DocumentBuilderFactory.newInstance();
		docBuilder = docFactory.newDocumentBuilder();
		doc = docBuilder.newDocument();
		
		transformerFactory = TransformerFactory.newInstance();
		transformer = transformerFactory.newTransformer();
		
		source = new DOMSource(doc);
		rootElement = doc.createElement(rootElementName);
		list = new ArrayList<Element>();
	}
	
	public static void commit() throws TransformerException
	{
		doc.appendChild(rootElement);
		transformerFactory = TransformerFactory.newInstance();
		transformer = transformerFactory.newTransformer();
		source = new DOMSource(doc);
		result = new StreamResult(f);
		transformer.transform(source, result);
		System.out.println(f.getAbsolutePath());
	}
	public static void createEmptyChild(String elementName){
		childElement = doc.createElement(elementName);
		list.add(childElement);
	}
	public static void createChildWithValue(String elementName,String elementValue){
		childElement = doc.createElement(elementName);
		childElement.appendChild(doc.createTextNode(elementValue));
		list.add(childElement);
	}
	public static void appendChildElement()
	{
		if(!list.isEmpty()){
			Iterator<Element> itr = list.iterator();
			while(itr.hasNext()){
				parentElement.appendChild(itr.next());			
			}
			rootElement.appendChild(parentElement);
		}
	}
	public static void createParentElement(String elementName){
		parentElement = doc.createElement(elementName);
	}
}
